package com.example.zbh.dsliao.ui.activty;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.model.entity.SearchSingerDetails;
import com.example.zbh.dsliao.presenter.SearchSingerPresenter;
import com.example.zbh.dsliao.ui.adapter.SearchSingerAdapter;
import com.example.zbh.dsliao.ui.viewinterface.ShowDownLoaderResultListener;
import com.example.zbh.dsliao.utils.FormatTime;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.net.VolleySingleton;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by yaolin on 15/11/28.
 */
public class SearchSingerActivity extends MVPBaseActivity<ShowDownLoaderResultListener, SearchSingerPresenter> implements View.OnClickListener, SearchSingerAdapter.setOnClickListener, SeekBar.OnSeekBarChangeListener, ShowDownLoaderResultListener {
    private TextView titleTv;
    private ImageView back_img;

    private ImageView img_play, img_previous, img_next;
    private TextView song, maxTv, progressTv;
    private SeekBar progress;

    //广播
    private MyBroadcastReceiver receiver;


    private List<SearchSingerDetails> list;
    private  Intent intent;

    //列表
    private RecyclerView rVSearchSinger;
    private SearchSingerAdapter adapter;

    //获得值
    private int id;

    //网络请求
    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    //当前位置
    private int currentIndex;

    //播放的接口操作对象
    private MusicIdle musicIdle;
    //服务连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //初始化接口操作对象
            musicIdle = MusicIdle.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected int getLayOut() {
        return  R.layout.activity_search_singer;
    }

    @Override
    protected void initView() {
        titleTv = findeView(R.id.titleTv);
        back_img = findeView(R.id.back_img);
        back_img.setOnClickListener(this);


        img_play = findeView(R.id.img_play);
        img_play.setOnClickListener(this);
        img_previous = findeView(R.id.img_previous);
        img_previous.setOnClickListener(this);
        img_next = findeView(R.id.img_next);
        img_next.setOnClickListener(this);
        song = findeView(R.id.song);            //歌名 + 歌手
        maxTv= findeView(R.id.tv_time_max); //歌曲时长
        progressTv = findeView(R.id.tv_time_progress);
        progress = findeView(R.id.progress);     //拖动条
        progress.setOnSeekBarChangeListener(this);

        rVSearchSinger = findeView(R.id.rVSearchSinger);
        GridLayoutManager gm = new GridLayoutManager(this, 1);
        rVSearchSinger.setLayoutManager(gm);

        adapter = new SearchSingerAdapter();
        rVSearchSinger.setAdapter(adapter);
    }



    @Override
    protected void initData() {
        getData();
//        requestContent();
        createPresenter().startSearchSingerConnection(getUrl());
        adapter.setListener(this);

        //注册EventBus
        EventBus.getDefault().register(this);
        //开启服务
        intent = new Intent("com.lanou.service.player");
        bindService(intent, conn, BIND_AUTO_CREATE);


        //注册自定义动态广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.lanou.player.next");
        filter.addAction("com.lanou.player.previous");
        receiver = new MyBroadcastReceiver();
        registerReceiver(receiver, filter);
    }

    public void onEvent(MyEventBus.CurrentIndex currentIndex) {
        Log.d("SongListActivity", "currentIndex:" + currentIndex);
        progress.setProgress(currentIndex.getCurrentIndex());
        progressTv.setText(FormatTime.formatTime((long) currentIndex.getCurrentIndex()));
    }

    public void onEvent(MyEventBus.MaxProgress maxProgress) {
        Log.d("SongListActivity", "currentIndex:" + maxProgress);
        progress.setMax(maxProgress.getMaxProgress());
    }

    @Override
    public void showResult(List list) {
        this.list = list;
        if (list != null){
            SearchSingerDetails s = (SearchSingerDetails) list.get(0);
            //titleTv.setText(s.getSingerName());
        }
        adapter.addData(list);


    }

    @Override
    public void showOtherResult(List list) {

    }


    public  class  MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.lanou.player.next")){
                if (musicIdle != null){
                    currentIndex ++;
                }
            } else if(intent.getAction().equals("com.lanou.player.previous")){
                if (musicIdle != null) {
                    currentIndex--;
                }
            }
            if (currentIndex < 0){
                Toast.makeText(SearchSingerActivity.this,"当前已经是第一首", Toast.LENGTH_SHORT).show();


            }else {

                img_play.setImageResource(R.mipmap.deep_pause_btn);
                String url = list.get(currentIndex).getAuditionList().get(0).getUrl();
                song.setText(list.get(currentIndex % list.size()).getName());
                maxTv.setText(FormatTime.formatTime((long) list.get(currentIndex).getAuditionList().get(0).getDuration()));
                try {
                    musicIdle.setUrl(url);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }


        }
    }

    /**
     * 获得值
     * **/
    private void getData() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", -1);
    }
    public String getUrl(){
        return Constant.SEARCHSINGERINFRONT+ id  + Constant.SEARCHSINGERLATEURL;
    }


    /**监听事件**/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_img:         //后退
                finish();
                break;
            case R.id.img_play:       //播放
               play();
                break;
            case R.id.img_previous:   //上一首
                previous();
                break;
            case R.id.img_next:       //下一首
               next();
                break;

        }
    }

    /**下一首**/
    private void next() {
        try {
            if (musicIdle != null) {
                musicIdle.next();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**上一首**/
    private void previous() {
        if(musicIdle != null){
            try {
                musicIdle.previous();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    /**播放**/
    private void play() {
        try {
            if (musicIdle != null) {
                musicIdle.pause();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**列表的行监听事件**/
    @Override
    public void onItemClick(SearchSingerDetails datas, int position) {
        try {
            if (musicIdle != null) {
                musicIdle.setUrl(datas.getAuditionList().get(0).getUrl());
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                song.setText(datas.getName());
                maxTv.setText(FormatTime.formatTime((long) datas.getAuditionList().get(0).getDuration()));
                currentIndex = position;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**seekBar监听事件**/
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        try {
            if (musicIdle != null) {
                musicIdle.setProgress(seekBar.getProgress());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected SearchSingerPresenter createPresenter() {
        return new SearchSingerPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        stopService(intent);

        unregisterReceiver(receiver);
        EventBus.getDefault().unregister(this);
    }
}
